/**
 * 
 */
package org.wangh.csv.functions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.wangh.csv.def.CSVCell;
import org.wangh.csv.def.Row;

import com.csvreader.CsvReader;

/**
 * @author he
 *
 */
public class ImportFromFile implements IFunction{
	
	private final String path;
	
	private final Character delimiter;
	
	private final Charset charset;
	
	private String filename;
	
	private List<Row> rows;
	
	public ImportFromFile(String path){
		this(path, null, null);
	}
	
	public ImportFromFile(String path, Character delimiter){
		this(path, delimiter, null);
	}
	
	public ImportFromFile(String path, Character delimiter, Charset charset){
		this.path = path;
		this.delimiter = delimiter;
		this.charset = charset;
	}
	
	public void run(){
		
		try {
			CsvReader reader = getReader();
			reader.readHeaders();
			String[] headers = reader.getHeaders();
			
			if(rows == null){
				rows = new ArrayList<Row>();
			}
			
			Row headerRow = buildHeader(headers);
			rows.add(headerRow);
			
			while(reader.readRecord()){
				Row row = new Row();
				row.setIsHeader(false);
				for(String header : headers){
					CSVCell cell = new CSVCell(header);
					String value = reader.get(header);
					cell.setContect(value);
					row.add(cell);
				}
				rows.add(row);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private CsvReader getReader(){
		
		CsvReader reader = null;
		
		try {
			
			//init the reader
			//if charset is null, use path to init
			//if charset is not null, then use inputstream.
			if(charset == null){
				reader = new CsvReader(path);
			}else{
				File file = new File(path);
				filename = file.getName();
				InputStream in = new FileInputStream(file);
				reader = new CsvReader(in, charset);
			}
			reader.setDelimiter(delimiter);
			
			return reader;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private Row buildHeader(String[] headers){
		Row row = new Row();
		row.setIsHeader(true);
		for(String header : headers){
			CSVCell cell = new CSVCell(header);
			row.add(cell);
		}
		return row;
	}
	
	public List<Row> getResult(){
		return rows;
	}

	@Override
	public boolean isValid() {
		return true;
	}
	
	public String getFileName(){
		return filename == null ? "CSVFILE" : filename;
	}
}
